package com.example.victory.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.victory.config.Const;
import com.example.victory.config.ServiceError;
import com.example.victory.entity.companyEntity.*;
import com.example.victory.mapper.CustomerMapper;
import com.example.victory.mapper.UserMapper;
import com.example.victory.mysql.DeptAndAccountMysqlMapper;
import com.example.victory.service.fsdp.FsdpUtilService;
import com.example.victory.swagger.handler.MiniAppApiDelegate;
import com.example.victory.swagger.model.*;
import com.example.victory.utils.CrmUtils;
import com.example.victory.utils.JsonUtils;
import com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequesFsdp;
import com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequesFsdpData;
import com.cgws.fintech.sdk.api.inner.crmapi.model.ApiResponseFsdp;
import com.cgws.fintech.sdk.api.inner.security.model.User;
import com.cgws.fintech.sdk.api.mvp.model.ApiRequestCustomerQuery;
import com.cgws.fintech.sdk.api.mvp.model.ApiRequestCustomerQueryData;
import com.cgws.fintech.sdk.api.mvp.model.ApiResponseCustomerQuery;
import com.cgws.fintech.sdk.api.mvp.model.CustomerAccount;
import com.cgws.fintech.sdk.common.cache.RedisService;
import com.cgws.fintech.sdk.common.exception.GlobalError;
import com.cgws.fintech.sdk.common.exception.GlobalException;
import com.cgws.fintech.sdk.common.utils.DateHelper;
import com.cgws.fintech.sdk.common.utils.MoneyHelper;
import com.example.victory.common.web.ServiceHelper;
import com.cgws.fintech.sdk.inner.utils.web.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class MiniAppApiService implements MiniAppApiDelegate {
    @Autowired
    private SessionService sessionService;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptAndAccountMysqlMapper deptAndAccountMysqlMapper;

    @Autowired
    private CustomerStatusService customerStatusService;

    @Autowired
    private MvpLoginService mvpLoginService;
    @Autowired
    private InnerNewOpenCustFsdpService innerNewOpenCustFsdpService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private FsdpUtilService fsdpUtilService;

    private void checkCustomerCollectType(String customerStausTkhlbGz,String isStore){

        if(StringUtils.isEmpty(customerStausTkhlbGz)&&isStore.equals("0")){
            throw new GlobalException(ServiceError.CUSTOMER_IS_STORE_FAIL);
        }
        if(!StringUtils.isEmpty(customerStausTkhlbGz)&&isStore.equals("1")) {
            throw new GlobalException(ServiceError.CUSTOMER_IS_STORE_FAIL);
        }
    }

    @Override
    @Transactional
    public ResponseEntity<ApiResponseNull> clickCustomerCollect(ApiRequestClickCollect param) {
        User user = sessionService.getCurrentUserSession(true).getUser();

        String customerId = param.getData().getCustomerId();
        ApiRequestClickCollectData.TypeEnum type = param.getData().getType();
        String  isStore= param.getData().getIsStore();
        ServiceHelper.checkDataNotNull(customerId, "customerId");
        ServiceHelper.checkDataNotNull(isStore, "isStore");
        ServiceHelper.checkDataNotNull(type, "type");
        Integer accountId = getCustomerAccount(user);
        switch (type) {
            case CUSTOMER:
                String customerStausTkhlbGz= customerMapper.getTkhlbGzByCustomerIdAndId(customerId,accountId);
                checkCustomerCollectType(customerStausTkhlbGz,isStore);
                if(!StringUtils.isEmpty(customerStausTkhlbGz)){
                    customerMapper.deleteTkhlbGzByCustomerIdAndId(customerId,accountId);
                }else {
                    customerMapper.insertTkhlbGz(customerId,accountId);
                }
                break;
            case SAVE:
                String customerStausTxkhhGz=customerMapper.getTxkhhGzByCustomerIdAndId(customerId,accountId);
                checkCustomerCollectType(customerStausTxkhhGz,isStore);
                if(!StringUtils.isEmpty(customerStausTxkhhGz)){
                    customerMapper.deleteTxkkhGzByCustomerIdAndId(customerId,accountId);
                }else {
                    customerMapper.insertTxkkhGz(customerId,accountId);
                }
                break;
            case BUSINESS:
                String customerStausTywjhGz=customerMapper.getTywjhGzByCustomerIdAndId(customerId,accountId);
                checkCustomerCollectType(customerStausTywjhGz,isStore);
                if(!StringUtils.isEmpty(customerMapper.getTywjhGzByCustomerIdAndId(customerId,accountId))){
                    customerMapper.deleteTywjhGzByCustomerIdAndId(customerId,accountId);
                }else {
                    customerMapper.insertTywjhGz(customerId,accountId);
                }
                break;
            default:
                throw new GlobalException(ServiceError.CUSTOMER_TYPE_FAIL);
        }

        return ResponseEntity.ok(new ApiResponseNull());
    }


    /**
     * 获取客户账号状态信息
     *
     * @param param 请求参数
     * @return 请求结果
     */
    @Override
    public ResponseEntity<ApiResponseAccountStatus> getCustomerAccountStatus(ApiRequestCustomerId param) {
        ServiceHelper.checkDataNotNull(param.getData(), "data");
        String customerId = param.getData().getCustomerId();
        ServiceHelper.checkDataNotNull(customerId, "customerId");
        List<AccountStatus> accountStatuses = new ArrayList<>();

        JSONObject fsdpParam = new JSONObject();
        fsdpParam.put("I_KHH", customerId);
        String result = fsdpUtilService.requestFsdp(fsdpParam, Const.FSDP_C_ACCOUNT_AUTHORITY);
        JSONArray jsonArray = JSONObject.parseArray(result);
        if (jsonArray != null && jsonArray.size() > 0) {
            JSONObject jsonRes = (JSONObject) jsonArray.get(0);

            ResponseEntity<ApiResponseCustomerStatus> apiResponseCustomerStatusResponseEntity= customerStatusService.getCRMCustomerStatus(customerId);
            if(apiResponseCustomerStatusResponseEntity.getStatusCode()!= HttpStatus.OK)
                return ResponseEntity.ok(new ApiResponseAccountStatus().data(new ApiResponseAccountStatusData().items(accountStatuses)));

            CustomerRightsAll customerRightsAll= apiResponseCustomerStatusResponseEntity.getBody().getRightsAll();

            final String OPEN_STATE = "1";
            AccountStatus ShA=new AccountStatusEntity();
            ShA.setCustomerId(customerId);
            ShA.setAccountName("上证A股");
            ShA.setStatus(OPEN_STATE.equals(jsonRes.getString("SHA")) ?  AccountStatusEnum.OPEN : AccountStatusEnum.UNOPEN);
            accountStatuses.add(ShA);

            AccountStatus ShB=new AccountStatusEntity();
            ShB.setCustomerId(customerId);
            ShB.setAccountName("上证B股");
            ShB.setStatus(OPEN_STATE.equals(jsonRes.getString("SHB")) ?  AccountStatusEnum.OPEN : AccountStatusEnum.UNOPEN);
            accountStatuses.add(ShB);

            AccountStatus SzA=new AccountStatusEntity();
            SzA.setCustomerId(customerId);
            SzA.setAccountName("深证A股");
            SzA.setStatus(OPEN_STATE.equals(jsonRes.getString("SZA")) ? AccountStatusEnum.OPEN : AccountStatusEnum.UNOPEN);
            accountStatuses.add(SzA);

            AccountStatus SzB=new AccountStatusEntity();
            SzB.setCustomerId(customerId);
            SzB.setAccountName("深证B股");
            SzB.setStatus(OPEN_STATE.equals(jsonRes.getString("SZB")) ? AccountStatusEnum.OPEN : AccountStatusEnum.UNOPEN);
            accountStatuses.add(SzB);

            AccountStatus Cyb=new AccountStatusEntity();
            Cyb.setCustomerId(customerId);
            Cyb.setAccountName("创业板");
            Cyb.setStatus(OPEN_STATE.equals(jsonRes.getString("CYB")) ? AccountStatusEnum.OPEN : AccountStatusEnum.UNOPEN);
            accountStatuses.add(Cyb);

            AccountStatus Xsb=new AccountStatusEntity();
            Xsb.setCustomerId(customerId);
            Xsb.setAccountName("新三板");
            Xsb.setStatus(Integer.parseInt(jsonRes.getString("XSB")) > 0 ? AccountStatusEnum.OPEN : AccountStatusEnum.UNOPEN);
            accountStatuses.add(Xsb);

            AccountStatus StockOpt=new AccountStatusEntity();
            StockOpt.setCustomerId(customerId);
            StockOpt.setAccountName("个股期权");
            StockOpt.setStatus(OPEN_STATE.equals(jsonRes.getString("GGQQ")) ? AccountStatusEnum.OPEN : AccountStatusEnum.UNOPEN);
            accountStatuses.add(StockOpt);

            AccountStatus ShHk=new AccountStatusEntity();
            ShHk.setCustomerId(customerId);
            ShHk.setAccountName("科创板");
            ShHk.setStatus(OPEN_STATE.equals(jsonRes.getString("KCB")) ? AccountStatusEnum.OPEN : AccountStatusEnum.UNOPEN);
            accountStatuses.add(ShHk);

            AccountStatus SzHk=new AccountStatusEntity();
            SzHk.setCustomerId(customerId);
            SzHk.setAccountName("港股通");
            AccountStatusEnum ggtStatus = AccountStatusEnum.UNOPEN;
            if(OPEN_STATE.equals(jsonRes.getString("SGT")) || OPEN_STATE.equals(jsonRes.getString("HGT"))){
                ggtStatus = AccountStatusEnum.OPEN;
            }
            SzHk.setStatus(ggtStatus);
            accountStatuses.add(SzHk);

            AccountStatus Rzrq=new AccountStatusEntity();
            Rzrq.setCustomerId(customerId);
            Rzrq.setAccountName("融资融券");
            Rzrq.setStatus(OPEN_STATE.equals(jsonRes.getString("RZRQ")) ? AccountStatusEnum.OPEN : AccountStatusEnum.UNOPEN);
            accountStatuses.add(Rzrq);
        }

        return ResponseEntity.ok(new ApiResponseAccountStatus().data(new ApiResponseAccountStatusData().items(accountStatuses)));
    }

    /**
     * 获取客户信用交易信息
     *
     * @param param 请求信息
     * @return 请求结果
     */
    @Override
    public ResponseEntity<ApiResponseCreditExchange> getCustomerCreditExchange(ApiRequestCustomerId param) {
        ServiceHelper.checkDataNotNull(param.getData(), "data");
        String customerId = param.getData().getCustomerId();
        ServiceHelper.checkDataNotNull(customerId, "customerId");

        CreditExchange exchange = customerMapper.getCreditExchange(customerId);
        if(exchange!=null){
            exchange.setProfitLoss(customerMapper.getCreditExchangeProfitLoss(customerId));
        }
        return ResponseEntity.ok(new ApiResponseCreditExchange().data(exchange));
    }

    /**
     * 获取客户信用交易持仓信息
     *
     * @param param 请求信息
     * @return 请求结果
     */
    @Override
    public ResponseEntity<ApiResponseStockPositions> getCustomerCreditPositions(ApiRequestCustomerId param) {
        ServiceHelper.checkDataNotNull(param.getData(), "data");
        String customerId = param.getData().getCustomerId();
        ServiceHelper.checkDataNotNull(customerId, "customerId");

        List<StockPosition> stockPositions = customerMapper.getCreditExchangeStockPosition(customerId);

        return ResponseEntity.ok(new ApiResponseStockPositions().data(new ApiResponseStockPositionsData().items(stockPositions)));
    }


    /**
     * 获取客户基本信息
     *
     * @param param 请求信息
     * @return 请求结果
     */
    @Override
    public ResponseEntity<ApiResponseCustomer> getCustomerInfo(ApiRequestCustomerId param) {
        ServiceHelper.checkDataNotNull(param.getData(), "data");
        String customerId = param.getData().getCustomerId();
        ServiceHelper.checkDataNotNull(customerId, "customerId");
//        User user = sessionService.getCurrentUserSession(true).getUser();
//        Integer accountId= getCustomerAccount(user);

        List<CustomerEntity> customerEntities = customerMapper.getCustomer(customerId);
        if (customerEntities == null ||customerEntities.size()==0) {
            throw new GlobalException(GlobalError.GLOBAL_NOT_FOUND_ID, customerId);
        }

        CustomerEntity customerEntity=customerEntities.get(0);
//        List<Integer> gxlxList= customerMapper.queryCustomerGxlxByCustomerId(customerId,accountId);
//        if(gxlxList!=null&&gxlxList.size()>0){
//            List<CustomerTypeName> customerTypeNameList=new ArrayList<>();
//            CustomerTypeName customerTypeName=new CustomerTypeName();
//            if(gxlxList.contains(10)){
//                customerTypeName.setType(CustomerType.DEVELOP);
//            }else if(gxlxList.contains(2)){
//                customerTypeName.setType(CustomerType.SIGN);
//            } else if(gxlxList.contains(1)){
//                customerTypeName.setType(CustomerType.SERVICE);
//            }
//            customerTypeNameList.add(customerTypeName);
//            customerEntity.setTypes(customerTypeNameList);
//        }
        Customer customerReturn = customerEntity.toCustomer();
//        if (customerReturn.getTypes() != null) {
//            if (customerReturn.getTypes() == null) {
//                customerReturn.setTypes(new ArrayList<>());
//            }
//        }

        customerReturn.setOptionExchageActive(!StringUtils.isEmpty(customerMapper.getStockOptByCustomerId(customerId))?Boolean.TRUE:Boolean.FALSE);
        customerReturn.setCreditExchageActive(!StringUtils.isEmpty(customerMapper.getRzrqByCustomerId(customerId))?Boolean.TRUE:Boolean.FALSE);
        //customerReturn.setOtcExchageActive(!StringUtils.isEmpty(customerMapper.getOtcByCustomerId(customerId))?Boolean.TRUE:Boolean.FALSE);
        customerReturn.setOtcExchageActive(Boolean.TRUE);//更改TOC默认为展示
        customerReturn.setNormalExchageActive(Boolean.TRUE);

        ResponseEntity<ApiResponseCustomerQuery> customerQueryResponseEntit=null;
        try {
            ApiRequestCustomerQuery customerQuery=new ApiRequestCustomerQuery();
            List<ApiRequestCustomerQueryData> customerQueryDataList=new ArrayList<>();
            ApiRequestCustomerQueryData customerQueryData=new ApiRequestCustomerQueryData();
            customerQueryData.setCustNum(customerReturn.getCustomerId());
            customerQueryDataList.add(customerQueryData);
            customerQuery.setData(customerQueryDataList);
            customerQueryResponseEntit= mvpLoginService.queryQustomers(customerQuery);
            if(customerQueryResponseEntit.getStatusCode()==HttpStatus.OK){
                List<CustomerAccount> customerAccountList= customerQueryResponseEntit.getBody().getData().getList();
                if(customerAccountList!=null&&customerAccountList.size()>0){
                    customerReturn.setImId(customerAccountList.get(0).getFcid());
                }
            }
        }catch (Exception ex){
            // 不抛出错误，让客户其它信息能正常返回
            log.error("请求mvp获取客户im号错误,e={}", ex);
        }

        // 获取服务投顾
        List<CustomerManager> managers = customerMapper.getManagersByCustomerId(customerId);
        managers.forEach(customerManager -> {
            switch (customerManager.getGxlx()) {
                case 1:
                    customerReturn.setManager(customerManager.getManager());
                    break;
                case 2:
                    customerReturn.setInvestmentConsultant(customerManager.getManager());
                    break;
                case 10:
                    customerReturn.setAgent(customerManager.getManager());
                    break;
                default:
                    break;
            }
        });

        return ResponseEntity.ok(new ApiResponseCustomer().data(customerReturn));
    }

    @Override
    public ResponseEntity<ApiResponseMessages> getCustomerMot(ApiRequestCustomerId param) {
        return ResponseEntity.ok(new ApiResponseMessages());
    }

    /**
     * 获取客户普通交易信息
     *
     * @param param 请求信息
     * @return 请求结果
     */
    @Override
    public ResponseEntity<ApiResponseNormalExchange> getCustomerNormalExchange(ApiRequestCustomerId param) {
        ServiceHelper.checkDataNotNull(param.getData(), "data");
        String customerId = param.getData().getCustomerId();
        ServiceHelper.checkDataNotNull(customerId, "customerId");

        NormalExchangeEntity normalExchangeEntity = customerMapper.getNormalExchange(customerId);
        if (normalExchangeEntity != null) {
            // 查询总浮动盈亏
            Double value = customerMapper.getNormalExchangeProfitLoss(customerId);
            normalExchangeEntity.setProfitLoss(value);
        }
        return ResponseEntity.ok(new ApiResponseNormalExchange().data(normalExchangeEntity));
    }

    /**
     * 获取客户普通交易持仓信息
     *
     * @param param 请求信息
     * @return 请求结果
     */
    @Override
    public ResponseEntity<ApiResponseStockPositions> getCustomerNormalPositions(ApiRequestCustomerId param) {
        ServiceHelper.checkDataNotNull(param.getData(), "data");
        String customerId = param.getData().getCustomerId();
        ServiceHelper.checkDataNotNull(customerId, "customerId");

        List<StockPosition> stockPositions = customerMapper.getNormalExchangeStockPosition(customerId);

        return ResponseEntity.ok(new ApiResponseStockPositions().data(new ApiResponseStockPositionsData().items(stockPositions)));
    }

    @Override
    public ResponseEntity<ApiResponseOptionExchange> getCustomerOptionExchange(ApiRequestCustomerId param) {
        ServiceHelper.checkDataNotNull(param.getData(), "data");
        String customerId = param.getData().getCustomerId();
        ServiceHelper.checkDataNotNull(customerId, "customerId");

        OptionExchange stockPositions = customerMapper.getCustomerOptionExchange(customerId);
        if(stockPositions!=null){
            stockPositions.setProfitLoss(customerMapper.getCustomerOptionExchangerofitLoss(customerId));
        }
        return ResponseEntity.ok(new ApiResponseOptionExchange().data(stockPositions));
    }

    /**
     * 获取客户期权交易持仓信息
     *
     * @param param 请求信息
     * @return 请求结果
     */
    @Override
    public ResponseEntity<ApiResponseOptionPositions> getCustomerOptionPositions(ApiRequestCustomerId param) {
        ServiceHelper.checkDataNotNull(param.getData(), "data");
        String customerId = param.getData().getCustomerId();
        ServiceHelper.checkDataNotNull(customerId, "customerId");

        List<OptionPosition> stockPositions = customerMapper.getOptionExchangeStockPosition(customerId);

        return ResponseEntity.ok(new ApiResponseOptionPositions().data(new ApiResponseOptionPositionsData().items(stockPositions)));
    }

    /**
     * 获取客户Otc交易持仓信息
     *
     * @param param 请求信息
     * @return 请求结果
     */
    @Override
    public ResponseEntity<ApiResponseOtcPositions> getCustomerOtcPositions(ApiRequestCustomerId param) {
        ServiceHelper.checkDataNotNull(param.getData(), "data");
        String customerId = param.getData().getCustomerId();
        ServiceHelper.checkDataNotNull(customerId, "customerId");

        List<OtcPositionEntity> positions = customerMapper.getOtcExchangeStockPosition(customerId);
        List<OtcPosition> items=new ArrayList<>();
        if(positions!=null&&positions.size()>0){
            positions.stream().forEach(position ->{
                List<OtcPositionDetail> details=new ArrayList<>();
                OtcPosition otcPosition=new OtcPosition();
                otcPosition.setCode(position.getCode());
                otcPosition.setName(position.getName());
                otcPosition.setProfitLoss(position.getProfitLoss());
                //货币
                OtcPositionDetail total=new OtcPositionDetail();
                total.setName("总份额");
                total.setValue(position.getMarketValueTotal());
                total.setEmphasize(Boolean.FALSE);
                details.add(total);

                OtcPositionDetail availableShare=new OtcPositionDetail();
                availableShare.setName("可用份额");
                availableShare.setValue(position.getAvailableShare());
                availableShare.setEmphasize(Boolean.FALSE);
                details.add(availableShare);


                OtcPositionDetail marketValueTotal=new OtcPositionDetail();
                marketValueTotal.setName("证券市值");
                marketValueTotal.setValue(position.getMarketValueTotal());
                marketValueTotal.setEmphasize(Boolean.FALSE);
                details.add(marketValueTotal);

                OtcPositionDetail assetValue=new OtcPositionDetail();
                assetValue.setName("单位净值");
                assetValue.setValue(position.getAssetValue());
                assetValue.setEmphasize(Boolean.FALSE);
                details.add(assetValue);


                OtcPositionDetail profitLoss=new OtcPositionDetail();
                profitLoss.setName("累计收益");
                profitLoss.setValue(position.getProfitLoss());
                profitLoss.setEmphasize(Boolean.TRUE);
                details.add(profitLoss);

                OtcPositionDetail callPrice=new OtcPositionDetail();
                callPrice.setName("买入价格");
                callPrice.setValue(position.getCallPrice());
                callPrice.setEmphasize(Boolean.FALSE);
                details.add(callPrice);
                otcPosition.setDetails(details);
                items.add(otcPosition);
            });
        }

        return ResponseEntity.ok(new ApiResponseOtcPositions().data(new ApiResponseOtcPositionsData().items(items)));
    }


    private Integer getCustomerAccount(User user){
        String crmId = user.getCrmId();
        if (StringUtils.isEmpty(crmId)) {
            throw new GlobalException(ServiceError.ACCOUNT_NOT_EXISTS);
        }
        return Integer.parseInt(crmId);

    }

    private  void checkNewOpenCustomerAcitveType(ApiRequestNewOpenCustomersPage param){
        NewOpenCustomerFilter customerFilter = param.getData().getFilter();
        if(customerFilter!=null){
            String isIncome=customerFilter.getIsIncome();
            String isTrade=customerFilter.getIsTrade();
            if((StringUtils.isEmpty(isIncome)&&!StringUtils.isEmpty(isTrade))||(!StringUtils.isEmpty(isIncome)&&StringUtils.isEmpty(isTrade))){
                throw new GlobalException(ServiceError.CUSTOMER_ACTIVE_FAIL);
            }
            if(!StringUtils.isEmpty(isIncome)&&!StringUtils.isEmpty(isTrade)&&isIncome.equals("0")&&isTrade.equals("1")){
                throw new GlobalException(ServiceError.CUSTOMER_ACTIVE_TYPE_FAIL);
            }
        }

    }



    @Override
    public ResponseEntity<ApiResponseNewOpenCustomersPage> getNewOpenCustomersPage(ApiRequestNewOpenCustomersPage param) {
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("index",param.getData().getIndex());
        jsonObject.put("pageSize",param.getData().getPageSize());
        jsonObject.put("accountId",sessionService.getCurrentUserSession(true).getUser().getCrmId());
        jsonObject.put("sortDirection",param.getData().getSortDirection());
        if(param.getData().getFilter()!=null){
            jsonObject.put("isStore",param.getData().getFilter().getIsStore());
            jsonObject.put("isIncome",param.getData().getFilter().getIsIncome());
            jsonObject.put("isTrade",param.getData().getFilter().getIsTrade());
            jsonObject.put("capitalIncome",param.getData().getFilter().getCapitalIncome());
            jsonObject.put("tradeNum",param.getData().getFilter().getTradeNum());
            jsonObject.put("search",param.getData().getFilter().getSearch());
        }
        ResponseEntity<ApiResponseFsdp> fsdpResponseEntity= innerNewOpenCustFsdpService.getNewOpenCustomerPage((new ApiRequesFsdp().data(new ApiRequesFsdpData().params(jsonObject.toJSONString()))));
        ApiResponseNewOpenCustomersPageData data= JsonUtils.getResultEntity(fsdpResponseEntity,ApiResponseNewOpenCustomersPageData.class);
        data.setCount(JSONObject.parseObject(fsdpResponseEntity.getBody().getData().getResult()).getInteger("count"));
        return ResponseEntity.ok(new ApiResponseNewOpenCustomersPage().data(data));

//        User user = sessionService.getCurrentUserSession(true).getUser();
//        Integer accountId= getCustomerAccount(user);
//        checkNewOpenCustomerAcitveType(param);
//        List<NewOpenCustomerResp> items=new ArrayList<>();
//        List<CustomerPageEntity> customerEntities = customerMapper.getNewOpenCustomersPage(accountId,param.getData());
//        if(customerEntities==null||customerEntities.size()==0){
//            return ResponseEntity.ok(new ApiResponseNewOpenCustomersPage().data(new ApiResponseNewOpenCustomersPageData().items(items)));
//        }
//
//        List<ApiRequestCustomerQueryData> customerQueryDataList=new ArrayList<>();
//        customerEntities.stream().forEach(customerEntity -> {
//            ApiRequestCustomerQueryData customerQueryData=new ApiRequestCustomerQueryData();
//            customerQueryData.setCustNum(customerEntity.getCustomerId());
//            customerQueryDataList.add(customerQueryData);
//
//            NewOpenCustomerResp customerResp=new NewOpenCustomerResp();
//            customerResp.setCustomerId(customerEntity.getCustomerId());
//            customerResp.setName(customerEntity.getName());
//            customerResp.setId(customerEntity.getId());
//            customerResp.setRiskLevel(StringUtils.isEmpty(customerEntity.getRiskLevel())?null:customerEntity.getRiskLevel());
//            customerResp.setCustomerLevel(customerEntity.getCustomerLevel());
//            customerResp.setIsStore(customerEntity.getIsStore());
//            customerResp.setRelationType("开发");
//            customerResp.setPhone(customerEntity.getPhone());
//            customerResp.setIsIncome(customerEntity.getIsIncome().equals("0")?"0":"1");
//            customerResp.setIsTrade(Double.parseDouble(customerEntity.getIsIncome())>0&&Double.parseDouble(customerEntity.getNetCommission())>0?"1":"0");
//
//            List<CustomerRespNameValue> customerRespNameValueLists=new ArrayList<>();
//            CustomerRespNameValue total=new CustomerRespNameValue();
//            total.setName("总资产");
//            total.setValue( MoneyHelper.formatMoney(new BigDecimal(customerEntity.getTotal().trim())));
//            customerRespNameValueLists.add(total);
//
//            CustomerRespNameValue netInflow=new CustomerRespNameValue();
//            netInflow.setName("净流入");
//            netInflow.setValue( MoneyHelper.formatMoney(new BigDecimal(customerEntity.getNetInflow().trim())));
//            customerRespNameValueLists.add(netInflow);
//
//            CustomerRespNameValue tradeNum=new CustomerRespNameValue();
//            tradeNum.setName("交易量");
//            tradeNum.setValue( MoneyHelper.formatMoney(new BigDecimal(customerEntity.getTradeNum().trim())));
//            customerRespNameValueLists.add(tradeNum);
//
//            CustomerRespNameValue netCommission=new CustomerRespNameValue();
//            netCommission.setName("净佣金");
//            netCommission.setValue(MoneyHelper.formatMoney(new BigDecimal(customerEntity.getNetCommission().trim())));
//            customerRespNameValueLists.add(netCommission);
//
//            CustomerRespNameValue totalMarket=new CustomerRespNameValue();
//            totalMarket.setName("总市值");
//            totalMarket.setValue(MoneyHelper.formatMoney(new BigDecimal(customerEntity.getTotalMarket().trim())));
//            customerRespNameValueLists.add(totalMarket);
//
//            CustomerRespNameValue openDate=new CustomerRespNameValue();
//            openDate.setName("开户日期");
//            openDate.setValue(customerEntity.getOpenDate().trim());
//            customerRespNameValueLists.add(openDate);
//
//            customerResp.setNameValue(customerRespNameValueLists);
//            items.add(customerResp);
//        });
//
//
//        if(customerQueryDataList.size()>0){
//            ApiRequestCustomerQuery customerQuery=new ApiRequestCustomerQuery();
//            customerQuery.setData(customerQueryDataList);
//            ResponseEntity<ApiResponseCustomerQuery> customerQueryResponseEntit=null;
//            try {
//                customerQueryResponseEntit= mvpLoginService.queryQustomers(customerQuery);
//            }catch (Exception ex){
//                log.error("请求mvp错误,e={}",ex);
//                throw new GlobalException(ServiceError.QUERY_CUSTOMER_INFO);
//            }
//            if(customerQueryResponseEntit.getStatusCode()==HttpStatus.OK){
//                List<CustomerAccount> customerAccountList= customerQueryResponseEntit.getBody().getData().getList();
//                if(customerAccountList!=null&&customerAccountList.size()>0){
//                    items.stream().forEach(customer -> {
//                        customerAccountList.stream().forEach(customerAccount->{
//                            if(!StringUtils.isEmpty(customerAccount.getFcid())&&customer.getCustomerId().equals(customerAccount.getCustNum())){
//                                customer.setImId(customerAccount.getFcid());
//                                return;
//                            }
//                        });
//                    });
//                }
//            }
//        }


        //return ResponseEntity.ok(new ApiResponseNewOpenCustomersPage().data(new ApiResponseNewOpenCustomersPageData().items(items)));
    }

    /**
     * 获取我的客户列表，支持按上次返回的最后记录id进行下拉分页查询，默认以客户号码倒叙排序，支持按总资产、可用资产、风险评级排序
     *
     * @param param 请求参数
     * @return 请求结果
     */
    @Override
    public ResponseEntity<ApiResponseCustomers> getCustomersPage(ApiRequestCustomersPage param) {
        User user = sessionService.getCurrentUserSession(true).getUser();
        Integer accountId= getCustomerAccount(user);
        List<CustomerResp> items=new ArrayList<>();
        List<CustomerPageEntity> customerEntities = customerMapper.getCustomersPage(false, accountId, param.getData());
        if(customerEntities==null||customerEntities.size()==0){
            return ResponseEntity.ok(new ApiResponseCustomers().data(new ApiResponseCustomersData().items(items)));
        }

        List<ApiRequestCustomerQueryData> customerQueryDataList=new ArrayList<>();
        customerEntities.stream().forEach(customerEntity -> {
            ApiRequestCustomerQueryData customerQueryData=new ApiRequestCustomerQueryData();
            customerQueryData.setCustNum(customerEntity.getCustomerId());
            customerQueryDataList.add(customerQueryData);

            CustomerResp customerResp=new CustomerResp();
            customerResp.setCustomerId(customerEntity.getCustomerId());
            customerResp.setName(customerEntity.getName());
            customerResp.setId(customerEntity.getId());
            customerResp.setPhone(customerEntity.getPhone());
            customerResp.setRiskLevel(StringUtils.isEmpty(customerEntity.getRiskLevel())?null:customerEntity.getRiskLevel());
            customerResp.setCustomerLevel(customerEntity.getCustomerLevel());
            customerResp.setIsStore(customerEntity.getIsStore());
            customerResp.setIsActive(customerEntity.getIsActive());

            List<Integer> gxlxList= customerMapper.queryCustomerGxlxByCustomerId(customerEntity.getCustomerId(),accountId);
            if(gxlxList!=null&&gxlxList.size()>0){
                CustomerTypeName customerTypeName=new CustomerTypeName();
                if(gxlxList.contains(10)){
                    customerResp.setRelationType("10");
                }else if(gxlxList.contains(2)){
                    customerResp.setRelationType("2");
                } else if(gxlxList.contains(1)){
                    customerResp.setRelationType("1");
                }
            }

            List<CustomerRespNameValue> customerRespNameValueLists=new ArrayList<>();
            CustomerRespNameValue total=new CustomerRespNameValue();
            total.setName("总资产");
            total.setValue(MoneyHelper.formatMoney(new BigDecimal(customerEntity.getTotal().trim())));
            customerRespNameValueLists.add(total);

            CustomerRespNameValue turnoverRate=new CustomerRespNameValue();
            turnoverRate.setName("周转率");
            turnoverRate.setValue(customerEntity.getTurnoverRate().trim().equals("0.00")?"0":customerEntity.getTurnoverRate().trim());
            customerRespNameValueLists.add(turnoverRate);

            CustomerRespNameValue totalMarket=new CustomerRespNameValue();
            totalMarket.setName("总市值");
            totalMarket.setValue(MoneyHelper.formatMoney(new BigDecimal(customerEntity.getTotalMarket().trim())));
            customerRespNameValueLists.add(totalMarket);

            CustomerRespNameValue commissionAndRate=new CustomerRespNameValue();
            commissionAndRate.setName("佣金");
            commissionAndRate.setValue(MoneyHelper.formatMoney(new BigDecimal(customerEntity.getCommission().trim()))+(customerEntity.getCommissionRate().trim().equals("0.00")?"(0‰)":"("+customerEntity.getCommissionRate().trim()+"‰)"));
            customerRespNameValueLists.add(commissionAndRate);

            CustomerRespNameValue availableTotal=new CustomerRespNameValue();
            availableTotal.setName("可用资产");
            availableTotal.setValue(MoneyHelper.formatMoney(new BigDecimal(customerEntity.getAvailableTotal().trim())));
            customerRespNameValueLists.add(availableTotal);

            CustomerRespNameValue openDate=new CustomerRespNameValue();
            openDate.setName("开户日期");
            openDate.setValue(customerEntity.getOpenDate());
            customerRespNameValueLists.add(openDate);

            customerResp.setNameValue(customerRespNameValueLists);
            items.add(customerResp);
        });


        /**
         * 说明：这段注释是由于整个接口比较慢，暂时不需要显示这个 im ，所以先注释，但是后续是否可能继续显示，或者将这个功能做成定时同步到
         * 本地数据库，都是可能的。所以暂时注释而不是去掉。
         */
//        if(customerQueryDataList.size()>0){
//            ApiRequestCustomerQuery customerQuery=new ApiRequestCustomerQuery();
//            customerQuery.setData(customerQueryDataList);
//            ResponseEntity<ApiResponseCustomerQuery> customerQueryResponseEntit=null;
//            try {
//                 customerQueryResponseEntit= mvpLoginService.queryQustomers(customerQuery);
//            }catch (Exception ex){
//                log.error("请求mvp错误,e={}",ex);
//                throw new GlobalException(ServiceError.QUERY_CUSTOMER_INFO);
//            }
//            if(customerQueryResponseEntit.getStatusCode()==HttpStatus.OK){
//                List<CustomerAccount> customerAccountList= customerQueryResponseEntit.getBody().getData().getList();
//                if(customerAccountList!=null&&customerAccountList.size()>0){
//                    items.stream().forEach(customer -> {
//                        customerAccountList.stream().forEach(customerAccount->{
//                            if(!StringUtils.isEmpty(customerAccount.getFcid())&&customer.getCustomerId().equals(customerAccount.getCustNum())){
//                                customer.setImId(customerAccount.getFcid());
//                                return;
//                            }
//                        });
//                    });
//                }
//            }
//        }

        return ResponseEntity.ok(new ApiResponseCustomers().data(new ApiResponseCustomersData().items(items)));
    }


    @Override
    public ResponseEntity<ApiResponseNewOpenCustomers> getNewOpenCustomers() {
        User user = sessionService.getCurrentUserSession(true).getUser();
        Integer accountId= getCustomerAccount(user);
        Integer count= customerMapper.getNewOpenCustomers(accountId);
        ApiResponseNewOpenCustomersData newOpenCustomersData=new ApiResponseNewOpenCustomersData();
        newOpenCustomersData.setCount(count==null?0:count);
        return ResponseEntity.ok(new ApiResponseNewOpenCustomers().data(newOpenCustomersData));
    }


    public static String INNER_BUSINESS_CUSTOMER_CUSTOMER_COUNT="inner-business-customer:customer:count:";
    public static String INNER_BUSINESS_CUSTOMER_CUSTOMER_CAPITAL="inner-business-customer:customer:capital:";

    /**
     * 获取当前投顾的资产概览，包括我的客户数、今日净值、托管资产和净增资产
     *
     * @return 请求结果
     */
    @Override
    public ResponseEntity<ApiResponseDepOverview> getOverview(ApiRequestCustomersPage param) {
        User user = sessionService.getCurrentUserSession(true).getUser();

        ApiResponseDepOverviewData data = new ApiResponseDepOverviewData();
        try {
            FsdpResponseEntity result = fsdpUtilService.requestFsdpFullData(getFsdpParam(user, param), Const.FSDP_C_XSB_CUSTOMER_LIST);
            data.setCustomerCount(result.getO_KHS());
            data.setAssetTotal(MoneyHelper.formatMoney(result.getO_ZTGZC()));
        } catch (Exception e) {
            log.error("从fsdp获取客户数和从资产出现异常",e);
            Integer accountId= getCustomerAccount(user);
            // 获取客户总数
            Integer customerCount= 0;
            // 获取总资产
            BigDecimal assetTotal= BigDecimal.ZERO;
            data.setCustomerCount(customerCount);
            data.setAssetTotal(MoneyHelper.formatMoney(assetTotal));
        }

        return ResponseEntity.ok(new ApiResponseDepOverview().data(data));
    }

    private void checkCustomerSituation(String relationType, ApiRequestSituationData.AccountTypeEnum accountTypeEnum){
        if(accountTypeEnum==null) {
            throw new GlobalException(ServiceError.CUSTOMER_TYPE_FAIL);
        }
        if(accountTypeEnum.equals(ApiRequestSituationData.AccountTypeEnum.STAFF)){
            ServiceHelper.checkDataNotNull(relationType, "relationType");
            if(!relationType.equals("1")&&!relationType.equals("2")&&!relationType.equals("10")){
                throw new GlobalException(ServiceError.CUSTOMER_RELATION_TYPE_FAIL);
            }
        }

    }

    private List<ApiResponseLabelNameValue> getCaptil(Map<String,String> staffCaptilMap){
        List<ApiResponseLabelNameValue> capital =new ArrayList<>();
        if(staffCaptilMap==null) return capital;
        ApiResponseLabelNameValue capitalOneNameValue=new ApiResponseLabelNameValue();
        capitalOneNameValue.setLabel("<1万");
        capitalOneNameValue.setName(staffCaptilMap.get("ONERATE").trim().equals("0.00%")?"0%":staffCaptilMap.get("ONERATE").trim());
        capitalOneNameValue.setValue(staffCaptilMap.get("ONECOUNT").trim());
        capital.add(capitalOneNameValue);

        ApiResponseLabelNameValue capitalOneToTenNameValue=new ApiResponseLabelNameValue();
        capitalOneToTenNameValue.setLabel("1-10万");
        capitalOneToTenNameValue.setName(staffCaptilMap.get("ONETOTENRATE").trim().equals("0.00%")?"0%":staffCaptilMap.get("ONETOTENRATE").trim());
        capitalOneToTenNameValue.setValue(staffCaptilMap.get("ONETOTENCOUNT").trim());
        capital.add(capitalOneToTenNameValue);

        ApiResponseLabelNameValue capitalTenToFiftyNameValue=new ApiResponseLabelNameValue();
        capitalTenToFiftyNameValue.setLabel("10-50万");
        capitalTenToFiftyNameValue.setName(staffCaptilMap.get("TENTOFIFTYRATE").trim().equals("0.00%")?"0%":staffCaptilMap.get("TENTOFIFTYRATE").trim());
        capitalTenToFiftyNameValue.setValue(staffCaptilMap.get("TENTOFIFTYCOUNT").trim());
        capital.add(capitalTenToFiftyNameValue);

        ApiResponseLabelNameValue capitalFiftyToHudNameValue=new ApiResponseLabelNameValue();
        capitalFiftyToHudNameValue.setLabel("50-100万");
        capitalFiftyToHudNameValue.setName(staffCaptilMap.get("FIFTYTOHUNRATE").trim().equals("0.00%")?"0%":staffCaptilMap.get("FIFTYTOHUNRATE").trim());
        capitalFiftyToHudNameValue.setValue(staffCaptilMap.get("FIFTYTOHUNCOUNT").trim());
        capital.add(capitalFiftyToHudNameValue);

        ApiResponseLabelNameValue capitalHudNameValue=new ApiResponseLabelNameValue();
        capitalHudNameValue.setLabel(">100万");
        capitalHudNameValue.setName(staffCaptilMap.get("HUNDREDRATE").trim().equals("0.00%")?"0%":staffCaptilMap.get("HUNDREDRATE").trim());
        capitalHudNameValue.setValue(staffCaptilMap.get("HUNDREDCOUNT").trim());
        capital.add(capitalHudNameValue);

        return  capital;
    }


    private List<ApiResponseLabelNameValue> getGrade(Map<String,String> staffCaptilMap){
        List<ApiResponseLabelNameValue> capital =new ArrayList<>();
        if(staffCaptilMap==null) return capital;
        ApiResponseLabelNameValue capitalOneNameValue=new ApiResponseLabelNameValue();
        capitalOneNameValue.setLabel("一级");
        capitalOneNameValue.setName(staffCaptilMap.get("ONEGRADERATE").trim().equals("0.00%")?"0%":staffCaptilMap.get("ONEGRADERATE").trim());
        capitalOneNameValue.setValue(staffCaptilMap.get("ONEGRADE").trim());
        capital.add(capitalOneNameValue);

        ApiResponseLabelNameValue capitalOneToTenNameValue=new ApiResponseLabelNameValue();
        capitalOneToTenNameValue.setLabel("二级");
        capitalOneToTenNameValue.setName(staffCaptilMap.get("TWOGRADERATE").trim().equals("0.00%")?"0%":staffCaptilMap.get("TWOGRADERATE").trim());
        capitalOneToTenNameValue.setValue(staffCaptilMap.get("TWOGRADE").trim());
        capital.add(capitalOneToTenNameValue);

        ApiResponseLabelNameValue capitalTenToFiftyNameValue=new ApiResponseLabelNameValue();
        capitalTenToFiftyNameValue.setLabel("三级");
        capitalTenToFiftyNameValue.setName(staffCaptilMap.get("THREEGRADERATE").trim().equals("0.00%")?"0%":staffCaptilMap.get("THREEGRADERATE").trim());
        capitalTenToFiftyNameValue.setValue(staffCaptilMap.get("THREEGRADE").trim());
        capital.add(capitalTenToFiftyNameValue);

        ApiResponseLabelNameValue capitalFiftyToHudNameValue=new ApiResponseLabelNameValue();
        capitalFiftyToHudNameValue.setLabel("四级");
        capitalFiftyToHudNameValue.setName(staffCaptilMap.get("FOURGRADERATE").trim().equals("0.00%")?"0%":staffCaptilMap.get("FOURGRADERATE").trim());
        capitalFiftyToHudNameValue.setValue(staffCaptilMap.get("FOURGRADE").trim());
        capital.add(capitalFiftyToHudNameValue);

        ApiResponseLabelNameValue capitalHudNameValue=new ApiResponseLabelNameValue();
        capitalHudNameValue.setLabel("五级");
        capitalHudNameValue.setName(staffCaptilMap.get("FIVEGRADERATE").trim().equals("0.00%")?"0%":staffCaptilMap.get("FIVEGRADERATE").trim());
        capitalHudNameValue.setValue(staffCaptilMap.get("FIVEGRADE").trim());
        capital.add(capitalHudNameValue);

        return  capital;
    }

    private List<ApiResponseLabelNameValue> getAccount(List<Map<String,String>> accountMapList) {
        List<ApiResponseLabelNameValue> accountList=new ArrayList<>();
        if(accountList==null||accountMapList.size()==0) return accountList;
        accountMapList.stream().forEach(accountMap->{
            if(accountMap.get("LX").equals("1")){
                ApiResponseLabelNameValue acccount=new ApiResponseLabelNameValue();
                acccount.setLabel("股票客户");
                acccount.setName(accountMap.get("BYXZ").trim());
                acccount.setValue(accountMap.get("KHZS").trim());
                accountList.add(acccount);
            } else if(accountMap.get("LX").equals("2")){
                ApiResponseLabelNameValue acccount=new ApiResponseLabelNameValue();
                acccount.setLabel("信用客户");
                acccount.setName(accountMap.get("BYXZ").trim());
                acccount.setValue(accountMap.get("KHZS").trim());
                accountList.add(acccount);

            }else if(accountMap.get("LX").equals("3")){
                ApiResponseLabelNameValue acccount=new ApiResponseLabelNameValue();
                acccount.setLabel("个股期权客户");
                acccount.setName(accountMap.get("BYXZ").trim());
                acccount.setValue(accountMap.get("KHZS").trim());
                accountList.add(acccount);
            }
        });
        return  accountList;

    }


    @Override
    public ResponseEntity<ApiResponseSituation> getSituation(ApiRequestSituation param) {
        ApiRequestSituationData.AccountTypeEnum accountTypeEnum = param.getData().getAccountType();
        String relationType = param.getData().getRelationType();
        checkCustomerSituation(relationType, accountTypeEnum);
        User user = sessionService.getCurrentUserSession(true).getUser();
        Integer accountId = getCustomerAccount(user);

        ApiResponseSituationData situationData = null;
        if (accountTypeEnum.equals(ApiRequestSituationData.AccountTypeEnum.STAFF)) {
            situationData = new ApiResponseSituationData();
            Map<String, String> capitalMap = customerMapper.getStaffCaptil(accountId, relationType);
            situationData.setCustomerTotal(capitalMap.get("CUSTOMERTOTAL").trim());
            situationData.setCapital(getCaptil(capitalMap));
            situationData.setGrade(getGrade(customerMapper.getStaffGrade(accountId, relationType)));
            situationData.setAccount(getAccount(customerMapper.getStaffAccount(accountId, relationType)));
        } else {
            situationData = new ApiResponseSituationData();
            Map<String, String> capitalMap = customerMapper.getDeptCaptil(accountId);
            situationData.setCustomerTotal(capitalMap.get("CUSTOMERTOTAL").trim());
            situationData.setCapital(getCaptil(capitalMap));
            situationData.setGrade(getGrade(customerMapper.getDeptGrade(accountId)));
            situationData.setAccount(getAccount(customerMapper.getDeptAccount(accountId)));
        }
        return ResponseEntity.ok(new ApiResponseSituation().data(situationData));
    }



    private List<NameValueResp> getCapitalYearMonthDay(List<Map<String,String>>  capitalYearList){
        List<NameValueResp> nameValueResps=new ArrayList<>();
        if(capitalYearList==null||capitalYearList.size()==0) return nameValueResps;
        capitalYearList.stream().forEach(capitalYear->{
            NameValueResp nameValueResp=new NameValueResp();
            nameValueResp.setDate(capitalYear.get("ND").trim());
            nameValueResp.setCapital(capitalYear.get("ZC").trim());
            nameValueResps.add(nameValueResp);
        });
        return nameValueResps;
    }


    @Override
    public ResponseEntity<ApiResponseCapital> getCapital(ApiRequestSituation param) {
        ApiRequestSituationData.AccountTypeEnum accountTypeEnum = param.getData().getAccountType();
        String relationType = param.getData().getRelationType();
        checkCustomerSituation(relationType, accountTypeEnum);
        User user = sessionService.getCurrentUserSession(true).getUser();
        Integer accountId = getCustomerAccount(user);
        ApiResponseCapitalData capitalData = null;
        if (accountTypeEnum.equals(ApiRequestSituationData.AccountTypeEnum.STAFF)) {
            capitalData = new ApiResponseCapitalData();
            capitalData.setYear(getCapitalYearMonthDay(deptAndAccountMysqlMapper.getStaffYear(String.valueOf(accountId), relationType)));
            capitalData.setMonth(getCapitalYearMonthDay(deptAndAccountMysqlMapper.getStaffMonth(String.valueOf(accountId), relationType)));
            capitalData.setDay(getCapitalYearMonthDay(deptAndAccountMysqlMapper.getStaffDay(String.valueOf(accountId), relationType)));
        } else {
            capitalData = new ApiResponseCapitalData();
            ApiResponseCrmUserIdData crmUserIdData = userMapper.findUsersIdByTryxxId(String.valueOf(accountId));
            if (crmUserIdData != null && !StringUtils.isEmpty(crmUserIdData.getDepartmentCode())) {
                capitalData.setYear(getCapitalYearMonthDay(deptAndAccountMysqlMapper.getDeptYear(crmUserIdData.getDepartmentCode())));
                capitalData.setMonth(getCapitalYearMonthDay(deptAndAccountMysqlMapper.getDeptMonth(crmUserIdData.getDepartmentCode())));
                capitalData.setDay(getCapitalYearMonthDay(deptAndAccountMysqlMapper.getDeptDay(crmUserIdData.getDepartmentCode())));
            }

        }
        return ResponseEntity.ok(new ApiResponseCapital().data(capitalData));
    }


    private List<CommissionTradeNameValueResp> getCommissionAndTradeYearMonthDay(List<Map<String,String>>  capitalYearList){
        List<CommissionTradeNameValueResp> nameValueResps=new ArrayList<>();
        if(capitalYearList==null||capitalYearList.size()==0) return nameValueResps;
        capitalYearList.stream().forEach(capitalYear->{
            CommissionTradeNameValueResp nameValueResp=new CommissionTradeNameValueResp();
            nameValueResp.setDate(capitalYear.get("ND").trim());
            nameValueResp.setTrade(capitalYear.get("JYL").trim());
            nameValueResp.setCommission(capitalYear.get("YJ").trim());
            nameValueResps.add(nameValueResp);
        });
        return nameValueResps;
    }


    @Override
    public ResponseEntity<ApiResponseCommissionTrade> getCommissionAndTrade(ApiRequestSituation param) {
        ApiRequestSituationData.AccountTypeEnum accountTypeEnum= param.getData().getAccountType();
        String relationType=  param.getData().getRelationType();
        checkCustomerSituation(relationType,accountTypeEnum);
        User user = sessionService.getCurrentUserSession(true).getUser();
        Integer accountId= getCustomerAccount(user);
        ApiResponseCommissionTradeData commissionTradeData=null;
        if(accountTypeEnum.equals(ApiRequestSituationData.AccountTypeEnum.STAFF)){
            commissionTradeData=new ApiResponseCommissionTradeData();
            commissionTradeData.setYear(getCommissionAndTradeYearMonthDay(deptAndAccountMysqlMapper.getStaffYear(String.valueOf(accountId),relationType)));
            commissionTradeData.setMonth(getCommissionAndTradeYearMonthDay(deptAndAccountMysqlMapper.getStaffMonth(String.valueOf(accountId),relationType)));
            commissionTradeData.setDay(getCommissionAndTradeYearMonthDay(deptAndAccountMysqlMapper.getStaffDay(String.valueOf(accountId),relationType)));
        }else{
            commissionTradeData=new ApiResponseCommissionTradeData();
            ApiResponseCrmUserIdData crmUserIdData=userMapper.findUsersIdByTryxxId(String.valueOf(accountId));
            if(crmUserIdData!=null&&!StringUtils.isEmpty(crmUserIdData.getDepartmentCode())){
                commissionTradeData.setYear(getCommissionAndTradeYearMonthDay(deptAndAccountMysqlMapper.getDeptYear(crmUserIdData.getDepartmentCode())));
                commissionTradeData.setMonth(getCommissionAndTradeYearMonthDay(deptAndAccountMysqlMapper.getDeptMonth(crmUserIdData.getDepartmentCode())));
                commissionTradeData.setDay(getCommissionAndTradeYearMonthDay(deptAndAccountMysqlMapper.getDeptDay(crmUserIdData.getDepartmentCode())));
            }
        }
        return ResponseEntity.ok(new ApiResponseCommissionTrade().data(commissionTradeData));

    }

    // 根据客户关系类型获取客户列表和客户数量，默认1、2、10
    @Override
    public ResponseEntity<ApiResponseCustomers> getCustomersByFsdpPage(ApiRequestCustomersPage param) {
        if (param.getData().getFilter() == null) {
            param.getData().setFilter(new CustomerFilter());
        }
        if (StringUtils.isEmpty(param.getData().getFilter().getRelationType())) {
            param.getData().getFilter().setRelationType(";1;2;10;");
        }
        User user = sessionService.getCurrentUserSession(true).getUser();
        List<CustomerResp> items = new ArrayList<>();
        FsdpResponseEntity result = fsdpUtilService.requestFsdpFullData(getFsdpParam(user, param), Const.FSDP_C_XSB_CUSTOMER_LIST);
        JSONArray jsonArray = JSONObject.parseArray(result.getO_RESULT());
        Optional<JSONArray> resultJsonArray = Optional.ofNullable(jsonArray);
        if (resultJsonArray.isPresent()) {
            resultJsonArray.get().forEach(json -> {
                JSONObject jsonObj = (JSONObject) json;
                CustomerResp customerResp = new CustomerResp();
                customerResp.setCustomerId(getValueByKey(jsonObj, "CUSTOMERID"));
                customerResp.setName(getValueByKey(jsonObj, "NAME"));
                customerResp.setRelationType(getValueByKey(jsonObj, "GXLX"));
                customerResp.setRiskLevel(getValueByKey(jsonObj, "RISKLEVEL"));
                customerResp.setCustomerLevel(getValueByKey(jsonObj, "CUSTOMERLEVEL"));
                customerResp.isActive(getValueByKey(jsonObj, "ISACTIVE"));
                customerResp.setPhone(getValueByKey(jsonObj, "PHONE"));
                customerResp.isStore(getValueByKey(jsonObj, "ISSTORE"));

                List<CustomerRespNameValue> customerRespNameValueLists = new ArrayList<>();
                CustomerRespNameValue total = new CustomerRespNameValue();
                total.setName("总资产");
                total.setValue(getValueByKey(jsonObj, "TOTAL"));
                customerRespNameValueLists.add(total);

                CustomerRespNameValue turnoverRate = new CustomerRespNameValue();
                String turnoverRateString = getValueByKey(jsonObj, "TURNOVERRATE").trim();
                turnoverRate.setName("周转率");
                turnoverRate.setValue(turnoverRateString.equals("0.00") ? "0" : turnoverRateString);
                customerRespNameValueLists.add(turnoverRate);

                CustomerRespNameValue monthCommission = new CustomerRespNameValue();
                monthCommission.setName("月佣金");
                monthCommission.setValue(getValueByKey(jsonObj, "MYJ_BY"));
                customerRespNameValueLists.add(monthCommission);

                CustomerRespNameValue seasonCommission = new CustomerRespNameValue();
                seasonCommission.setName("季佣金");
                seasonCommission.setValue(getValueByKey(jsonObj, "MYJ_J3Y"));
                customerRespNameValueLists.add(seasonCommission);

                CustomerRespNameValue totalMarket = new CustomerRespNameValue();
                totalMarket.setName("总市值");
                totalMarket.setValue(getValueByKey(jsonObj, "TOTALMARKET"));
                customerRespNameValueLists.add(totalMarket);

                CustomerRespNameValue commissionAndRate = new CustomerRespNameValue();
                commissionAndRate.setName("佣金");
                commissionAndRate.setValue(getValueByKey(jsonObj, "COMMISSION"));
                customerRespNameValueLists.add(commissionAndRate);

                CustomerRespNameValue availableTotal = new CustomerRespNameValue();
                availableTotal.setName("可用资产");
                availableTotal.setValue(getValueByKey(jsonObj, "AVAILABLETOTAL"));
                customerRespNameValueLists.add(availableTotal);

                CustomerRespNameValue openDate = new CustomerRespNameValue();
                openDate.setName("开户日期");
                openDate.setValue(getValueByKey(jsonObj, "OPENDATE"));
                customerRespNameValueLists.add(openDate);

                customerResp.setNameValue(customerRespNameValueLists);

                items.add(customerResp);
            });
        }

        ApiResponseCustomersData data =  new ApiResponseCustomersData();
        data.setCustomerTotal(Long.valueOf(result.getO_KHS()));
        data.setAssetTotal(MoneyHelper.formatMoney(result.getO_ZTGZC()));
        data.items(items);
        return ResponseEntity.ok(new ApiResponseCustomers().data(data));
    }

    // 根据客户关系类型获取客户列表和客户数量，默认6、8
    @Override
    public ResponseEntity<ApiResponseCustomers> getCustomersFromFsdp(ApiRequestCustomersPage param) {
        User user = sessionService.getCurrentUserSession(true).getUser();
        List<CustomerResp> items = new ArrayList<>();
        if(param.getData().getFilter()==null){
            param.getData().setFilter(new CustomerFilter());
        }
        if( StringUtils.isEmpty(param.getData().getFilter().getRelationType())){
            param.getData().getFilter().setRelationType(";6;8;");
        }
        FsdpResponseEntity result = fsdpUtilService.requestFsdpFullData(getFsdpParam(user, param), Const.FSDP_C_XSB_CUSTOMER_LIST);
        JSONArray jsonArray = JSONObject.parseArray(result.getO_RESULT());
        Optional<JSONArray> resultJsonArray = Optional.ofNullable(jsonArray);
        if (resultJsonArray.isPresent()) {
            resultJsonArray.get().forEach(json -> {
                JSONObject jsonObj = (JSONObject) json;
                CustomerResp customerResp = new CustomerResp();
                customerResp.setCustomerId(getValueByKey(jsonObj, "CUSTOMERID"));
                customerResp.setName(getValueByKey(jsonObj, "NAME"));
                customerResp.setRelationType(getValueByKey(jsonObj, "GXLX"));
                customerResp.setRiskLevel(getValueByKey(jsonObj, "RISKLEVEL"));
                customerResp.setCustomerLevel(getValueByKey(jsonObj, "CUSTOMERLEVEL"));
                customerResp.isActive(getValueByKey(jsonObj, "ISACTIVE"));
                customerResp.setPhone(getValueByKey(jsonObj, "PHONE"));
                customerResp.isStore(getValueByKey(jsonObj, "ISSTORE"));

                List<CustomerRespNameValue> customerRespNameValueLists = new ArrayList<>();
                CustomerRespNameValue total = new CustomerRespNameValue();
                total.setName("总资产");
                total.setValue(getValueByKey(jsonObj, "TOTAL"));
                customerRespNameValueLists.add(total);

                CustomerRespNameValue turnoverRate = new CustomerRespNameValue();
                String turnoverRateString = getValueByKey(jsonObj, "TURNOVERRATE").trim();
                turnoverRate.setName("周转率");
                turnoverRate.setValue(turnoverRateString.equals("0.00") ? "0" : turnoverRateString);
                customerRespNameValueLists.add(turnoverRate);

                CustomerRespNameValue monthCommission = new CustomerRespNameValue();
                monthCommission.setName("月佣金");
                monthCommission.setValue(getValueByKey(jsonObj, "MYJ_BY"));
                customerRespNameValueLists.add(monthCommission);

                CustomerRespNameValue seasonCommission = new CustomerRespNameValue();
                seasonCommission.setName("季佣金");
                seasonCommission.setValue(getValueByKey(jsonObj, "MYJ_J3Y"));
                customerRespNameValueLists.add(seasonCommission);

                CustomerRespNameValue totalMarket = new CustomerRespNameValue();
                totalMarket.setName("总市值");
                totalMarket.setValue(getValueByKey(jsonObj, "TOTALMARKET"));
                customerRespNameValueLists.add(totalMarket);

                CustomerRespNameValue commissionAndRate = new CustomerRespNameValue();
                commissionAndRate.setName("佣金");
                commissionAndRate.setValue(getValueByKey(jsonObj, "COMMISSION"));
                customerRespNameValueLists.add(commissionAndRate);

                CustomerRespNameValue availableTotal = new CustomerRespNameValue();
                availableTotal.setName("可用资产");
                availableTotal.setValue(getValueByKey(jsonObj, "AVAILABLETOTAL"));
                customerRespNameValueLists.add(availableTotal);

                CustomerRespNameValue openDate = new CustomerRespNameValue();
                openDate.setName("开户日期");
                openDate.setValue(getValueByKey(jsonObj, "OPENDATE"));
                customerRespNameValueLists.add(openDate);

                customerResp.setNameValue(customerRespNameValueLists);
                items.add(customerResp);
            });
        }
        ApiResponseCustomersData data =  new ApiResponseCustomersData();
        data.setCustomerTotal(Long.valueOf(result.getO_KHS()));
        data.setAssetTotal(MoneyHelper.formatMoney(result.getO_ZTGZC()));
        data.items(items);
        return ResponseEntity.ok(new ApiResponseCustomers().data(data));
    }


    private JSONObject getFsdpParam(User user, ApiRequestCustomersPage param) {
        ApiRequestCustomersPageData data = param.getData();
        ServiceHelper.check(data != null, "data");
        Integer pageSize = data.getPageSize();
        Integer index = data.getIndex();
        Integer sort = null;
        ApiRequestCustomersPageData.SortByEnum sortBy = data.getSortBy();
        ApiRequestCustomersPageData.SortDirectionEnum sortDirection = data.getSortDirection();

        if (pageSize == null || pageSize <= 0) {
            pageSize = 20;
        }

        // 页码加1
        index = (index == null || index < 0) ? 1 : index + 1;

        if (sortBy == null) {
            sortBy = ApiRequestCustomersPageData.SortByEnum.DEFAULT;
        }
        if (sortDirection == null) {
            sortDirection = ApiRequestCustomersPageData.SortDirectionEnum.DESC;
        }
        String sortColumn;

        switch (sortBy) {
            case TOTAL:
                sortColumn = "total ";
                if (sortDirection == ApiRequestCustomersPageData.SortDirectionEnum.ASC)
                    sort = 1;
                else
                    sort = 2;
                break;
            case AVAILABLE_TOTAL:
                sortColumn = "availableTotal ";
                if (sortDirection == ApiRequestCustomersPageData.SortDirectionEnum.ASC)
                    sort = 3;
                else
                    sort = 4;
                break;
            case TURNOVER_RATE:
                sortColumn = "turnoverRate ";
                if (sortDirection == ApiRequestCustomersPageData.SortDirectionEnum.ASC)
                    sort = 5;
                else
                    sort = 6;
                break;
            case OPER_DATE:
                sortColumn = "openDate ";
                if (sortDirection == ApiRequestCustomersPageData.SortDirectionEnum.ASC)
                    sort = 7;
                else
                    sort = 8;
                break;
            case MYJ_BY:
                if (sortDirection == ApiRequestCustomersPageData.SortDirectionEnum.ASC)
                    sort = 9;
                else
                    sort = 10;
                break;
            case MYJ_J3Y:
                if (sortDirection == ApiRequestCustomersPageData.SortDirectionEnum.ASC)
                    sort = 10;
                else
                    sort = 11;
                break;
            default:
                sortColumn = "customerId ";
                break;
        }

        // 获取ryid
        Integer ryid = CrmUtils.getCustomerAccount(user);
        JSONObject fsdpParam = new JSONObject();
        fsdpParam.put("I_INDEX", index);
        fsdpParam.put("I_PAGESIZE", pageSize);
        fsdpParam.put("I_RYID", ryid);
        fsdpParam.put("I_SORT", sort);

        CustomerFilter customerFilter = data.getFilter();
        if (customerFilter != null) {
            CustomerFilterAsset asset = customerFilter.getAsset();
            if (asset != null) {
                AssetRange total = asset.getTotal();
                AssetRange totalMarket = asset.getTotalMarket();
                if (total != null) {
                    if (total.getMin() != null) {
                        fsdpParam.put("I_ZZC_ZDJ", total.getMin());
                    }
                    if (total.getMax() != null) {
                        fsdpParam.put("I_ZZC_ZGJ", total.getMax());
                    }
                }

                if (totalMarket != null) {
                    if (totalMarket.getMin() != null) {
                        fsdpParam.put("I_GPZC_ZDJ", totalMarket.getMin());
                    }
                    if (totalMarket.getMax() != null) {
                        fsdpParam.put("I_GPZC_ZGJ", totalMarket.getMax());
                    }
                }
            }
            Optional<String> customerLevelOpt = Optional.ofNullable(customerFilter.getCustomerLevel());
            if (customerLevelOpt.isPresent()) {
                fsdpParam.put("I_KHJB", Integer.parseInt(customerLevelOpt.get()));
            }
            Optional<String> isActiveOpt = Optional.ofNullable(customerFilter.getIsActive());
            if (isActiveOpt.isPresent()) {
                fsdpParam.put("I_LJSJHQK", Integer.parseInt(isActiveOpt.get()));
            }
            Optional<String> isStoreOpt = Optional.ofNullable(customerFilter.getIsStore());
            if (isStoreOpt.isPresent()) {
                fsdpParam.put("I_SFGZ", Integer.parseInt(isStoreOpt.get()));
            }
            Optional<String> relationTypeOpt = Optional.ofNullable(customerFilter.getRelationType());
            if (relationTypeOpt.isPresent()) {
                fsdpParam.put("I_KHGX", relationTypeOpt.get());
            }
            Optional<String> riskLevelOpt = Optional.ofNullable(customerFilter.getRiskLevel());
            if (riskLevelOpt.isPresent()) {
                fsdpParam.put("I_FXDJ", Integer.parseInt(riskLevelOpt.get()));
            }
            Optional<String> searchOpt = Optional.ofNullable(customerFilter.getSearch());
            if (searchOpt.isPresent()) {
                fsdpParam.put("I_SS", searchOpt.get());
            }
        }
        if (!fsdpParam.containsKey("I_KHGX")) {
            fsdpParam.put("I_KHGX",";1;2;10;");
        }
        return fsdpParam;
    }

    private String getValueByKey(JSONObject json, String key) {
        return !StringUtils.isEmpty(json.getString(key)) ? json.getString(key) : "";
    }

    @Override
    @Transactional
    public ResponseEntity<ApiResponseNull> clickCustomerCollectByFsdp(ApiRequestClickCollect param) {
        User user = sessionService.getCurrentUserSession(true).getUser();

        String customerId = param.getData().getCustomerId();
        ApiRequestClickCollectData.TypeEnum type = param.getData().getType();
        String  isStore= param.getData().getIsStore();
        ServiceHelper.checkDataNotNull(customerId, "customerId");
        ServiceHelper.checkDataNotNull(isStore, "isStore");
        ServiceHelper.checkDataNotNull(type, "type");
        Integer accountId = getCustomerAccount(user);

        String customerStausTxkhhGz=customerMapper.getTxkhhGzByCustomerIdAndId(customerId,accountId);
        checkCustomerCollectType(customerStausTxkhhGz,isStore);
        if(!StringUtils.isEmpty(customerStausTxkhhGz)){
            customerMapper.deleteTxkkhGzByCustomerIdAndId(customerId,accountId);
        }else {
            customerMapper.insertTxkkhGz(customerId,accountId);
        }

        JSONObject fsdpParam = new JSONObject();
        fsdpParam.put("I_KHH", customerId);
        fsdpParam.put("I_RYID", accountId);
        fsdpParam.put("I_LX", isStore.equalsIgnoreCase("1") ? 1 : -1);
        fsdpParam.put("I_GZRQ", Integer.parseInt(DateHelper.getDateYYYYMMDD(new Date())));
        fsdpUtilService.requestFsdp(fsdpParam, Const.FSDP_C_NEW_OPEN_CUSTOMER_STORE);


        return ResponseEntity.ok(new ApiResponseNull());
    }
}

